﻿package
{
	import com.lohika.*;
	import com.lohika.util.*;
	
	import events.GameEvent;
	
	import flash.display.*;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	
	/**
	 * Main application
	 * 
	 * @author Vitaly Vrublevskyy
	 */
	
	[SWF(width='1000',height='768',backgroundColor='#F0F0F0')]
	
	public class Main extends Sprite
	{
		public static var stageWidth:Number;
		public static var stageHeight:Number;
		
		private var factory:GameFactory;
		private var game:IGame;
		private var statWindow:Window;
		
		public function Main()
		{			
			addEventListener(Event.ADDED_TO_STAGE, init);
		}

		private function init(e:Event) : void
        {
			e.stopPropagation();
			
			stage.frameRate= 30;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.showDefaultContextMenu =  false;
			
			Main.stageWidth = stage.stageWidth;
			Main.stageHeight = stage.stageHeight;
			new DummyClass(); 

			stage.addEventListener(KeyboardEvent.KEY_UP, onHotKey);
			stage.addEventListener(Event.RESIZE, onResize);
			
			createApplication()
		}
		
		private function createApplication():void 
		{
			factory = new GameFactory();
			
			addEventListener(GameEvent.RESTART, onRestartGame);
			addEventListener(GameEvent.CONTINUED, onGamePaused);
			addEventListener(GameEvent.GAME_OVER, onGameOver);
			
			statWindow = new Window();
			addChild(statWindow);	
			
			createNewGame();
		}
		
		private function createNewGame():void
		{
			game = factory.createGame();
			game.start();
			position();
			addChildAt(game.container, 0);
		}		
		
		public function tearDownGame():void
		{
			removeChild(game.container);
			game.end();
			game = null;
		}
		
		/**
		 * Listeners
		 */		
		protected function onHotKey(event:KeyboardEvent):void
		{
			//"P" - PAUSE
			if (event.keyCode == 80) 
			{
				onGamePaused();
			}

			//"ESC" tear down game
			if (event.keyCode ==  27)
			{
				statWindow.appear(game.score, Constant.GAME_OVER); 
				GameUtil.playSound( new SoundGameOver() );
				tearDownGame();
			}
		}
		
		protected function onGameOver(event:GameEvent):void
		{
			event.stopPropagation();
			
			statWindow.appear(event.score, Constant.GAME_OVER); 
		}
		
		protected function onResize(event:Event):void
		{
			event.stopPropagation();
			position();
		}
		
		private function onRestartGame(...args):void
		{
			if (game)
				tearDownGame();

			createNewGame();
		}

		private function onGamePaused(...args):void
		{
			if ( game.pause() ) 
				statWindow.appear(game.score, Constant.PAUSE) 
			else
				statWindow.disappear();
		}
		
		private function position():void
		{
			game.container.x = (stage.stageWidth - game.container.width) / 2;
			game.container.y = (stage.stageHeight - game.container.height) / 2;
		}

	}//class

}//package